Slopes = NaN(16,3,3); % #coef * 3 types * 3 regions

for cntry = [55 50 51]
    switch cntry
        case 55, ctype = 1;
        case 50, ctype = 2; 
        case 51, ctype = 3;
    end
    
    AllY = []; AllX = [];
    for t = TFirst:THalf
        Y = Return(:,t);
        X = [Return11(:,t-2) squeeze(XVARS(:,t-1,1:7)) MV(:,t-1)];
        idx = isfinite(Y) & all(isfinite(X),2) & CountryRegionDummy(:,cntry) & ~IsREIT & ~IsMicro(:,t-2,cntry);
        if sum(idx)>MinStocks
            if WinsorizeYRet 
                y = winsorize(Y(idx),WinsorLevelY);
            else
                y = Y(idx);
            end
            x = winsorize(X(idx,:),WinsorLevelX);
            
            % neutralize country effects
            K = size(X,2);
            for cc = 1:49
                idx_cc = CountryRegionDummy(idx,cc);
                if sum(idx_cc) >= 1
                    for k = 1:K
                        x(idx_cc,k) = x(idx_cc,k) - mean(x(idx_cc,k),'omitnan');
                    end
                end
            end
            
            xs = standardize(x);
            % convert to residual analyst
            ytemp = xs(:,4); xtemp = [ones(sum(idx),1) xs(:,9)];
            xs(:,4) = ytemp - xtemp*(xtemp\ytemp);
            
            xs2 = [xs(:,1) repmat(xs(:,1),1,7).*xs(:,2:8) xs(:,2:8)];
            
            xx = xs2;
            %xx = [xs2 ones(length(y),1)]; % do not include intercept
            
            if any(sum(isfinite(xx))==0); continue; end
            if rank(xx) == size(xx,2)
                AllY = [AllY; y];
                AllX = [AllX; xx];
            end
        end
    end
    tic; [bL, fitinfoL] = lasso(AllX,AllY,'Standardize',false,'CV',10); toc;
    tic; [bE, fitinfoE] = lasso(AllX,AllY,'Standardize',false,'Alpha',0.5,'CV',10); toc;

    Nobs = length(AllY);
    bols = [AllX ones(Nobs,1)]\AllY;
    bLasso = [bL(:,fitinfoL.IndexMinMSE); fitinfoL.Intercept(fitinfoL.IndexMinMSE)];
    bEnet = [bE(:,fitinfoE.IndexMinMSE); fitinfoE.Intercept(fitinfoE.IndexMinMSE)];
    
    Slopes(:,:,ctype) = [bols bLasso bEnet];
    b = [bols bLasso bEnet];
    
    if cntry == 55
        writematrix(b,FileName, 'Sheet', SheetName, 'Range','b4:d18', 'AutoFitWidth',false);
    elseif cntry == 50
        writematrix(b,FileName, 'Sheet', SheetName, 'Range','f4:h18', 'AutoFitWidth',false);
    elseif cntry == 51
        writematrix(b,FileName, 'Sheet', SheetName, 'Range','j4:l18', 'AutoFitWidth',false);
    end
    %lassoPlot(b,fitinfo,'PlotType','Lambda','XScale','log');
    %lassoPlot(b,fitinfo,'PlotType','CV');
end
save Table6Data Slopes;
